const express = require('express');
const path = require('path');
const favicon = require('serve-favicon');
const morgan = require('morgan');
const cookieParser = require('cookie-parser');
const compression = require('compression');
const bodyParser = require('body-parser');
const mysql = require('mysql');
const session = require('express-session');
const MySQLStore = require('express-mysql-session')(session);
const logger = require('./modules/Logger');
const { Writable } = require('stream');

const Configure = require('./bin/Configure');
const index = require('./routes/index');
const users = require('./routes/users');

const app = express();
// 通过 gzip/deflate 压缩响应数据
app.use(compression());

// 结合morgan和log4js的日志功能
const logStream = new Writable({
    write(chunk) {
        logger.info(chunk.toString());
    },
});

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');

// uncomment after placing your favicon in /public
app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(morgan('short', { stream: logStream }));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser(Configure.secret));

// 根据进程数量决定是否使用数据库保存会话
if (process.env.multi) {
    // 多进程
    const pool = mysql.createPool(Configure.dbOptions);
    // checkExpirationInterval : How frequently expired sessions will be cleared; milliseconds.
    // expiration: The maximum age of a valid session; milliseconds
    const sessionStore = new MySQLStore({
        checkExpirationInterval: 1 * 1 * 3600 * 1000,
        expiration: 1 * 1 * 3600 * 1000,
    }, pool);

    app.use(session({
        name: 'sid',
        secret: Configure.secret,
        store: sessionStore,
        resave: false,
        saveUninitialized: true,
        // 将会话id保存到浏览器的cookie上
        // maxAge: null 表示关闭浏览器该session就失效
        cookie: {
            httpOnly: true,
            maxAge: null,
        },
    }));
} else {
    // 单进程
    app.use(session({
        name: 'sid',
        resave: false,
        secret: Configure.secret,
        saveUninitialized: true,
        cookie: {
            httpOnly: true,
            maxAge: null,
        },
    }));
}

app.use(express.static(path.join(__dirname, 'public'), { maxAge: 1 * 24 * 60 * 60 * 1000 }));

app.use('/', index);
app.use('/users', users);

// catch 404 and forward to error handler
app.use((req, res, next) => {
    const err = new Error('Not Found');
    err.status = 404;
    next(err);
});

// error handler
app.use((err, req, res, next) => {
    // set locals, only providing error in development
    res.locals.message = err.message;
    res.locals.error = req.app.get('env') === 'development' ? err : {};

    // render the error page
    res.status(err.status || 500);
    res.render('error');
    next();
});

// 处理未捕获异常
process.on('uncaughtException', (err) => {
    logger.fatal('ERROR UNCAUTCH', err);
});

module.exports = app;
